<template>
    <n-card>
        <n-form ref="formRef" label-placement="top" :label-width="80">
            <template v-for="item in list" :key="item.id">
                <n-form-item
                    v-if="item.configKey == 'server_msg_encrypt_type'"
                    :label="item.name"
                >
                    <n-radio-group v-model:value="item.configValue">
                        <n-space>
                            <n-radio value="1"> 明文模式</n-radio>
                            <n-radio value="2"> 兼容模式</n-radio>
                            <n-radio value="3"> 安全模式（推荐）</n-radio>
                        </n-space>
                    </n-radio-group>
                </n-form-item>
                <n-form-item v-else-if="item.configKey == 'limit_pay'" :label="item.name">
                    <n-radio-group v-model:value="item.configValue">
                        <n-space>
                            <n-radio value=""> 无限制</n-radio>
                            <n-radio value="no_credit"> 不能使用信用卡</n-radio>
                        </n-space>
                    </n-radio-group>
                </n-form-item>
                <n-form-item v-else-if="item.configKey == 'receipt'" :label="item.name">
                    <n-radio-group v-model:value="item.configValue">
                        <n-space>
                            <n-radio value="Y"> 开放</n-radio>
                            <n-radio value="no_credit"> 不开放</n-radio>
                        </n-space>
                    </n-radio-group>
                </n-form-item>
                <n-form-item
                    v-else-if="item.configKey == 'server_data_format'"
                    :label="item.name"
                >
                    <n-radio-group v-model:value="item.configValue">
                        <n-space>
                            <n-radio value="XML"> XML</n-radio>
                            <n-radio value="JSON"> JSON</n-radio>
                        </n-space>
                    </n-radio-group>
                </n-form-item>
                <n-form-item
                    v-else-if="item.configKey == 'server_domain_url'"
                    :label="item.name"
                >
                    <jb-input
                        v-model:value="item.configValue"
                        :maxlength="255"
                        :disabled="true"
                        :placeholder="`请输入${item.name}的值`"
                    ></jb-input>
                </n-form-item>
                <n-form-item
                    v-else-if="item.configKey == 'music_post_mediaid'"
                    :label="item.name"
                >
                    <jb-input
                        v-model:value="item.configValue"
                        :maxlength="255"
                        :disabled="true"
                        :placeholder="`请输入${item.name}的值`"
                    ></jb-input>
                </n-form-item>
                <n-form-item v-else :label="item.name" path="type">
                    <jb-input
                        v-model:value="item.configValue"
                        :maxlength="255"
                        :placeholder="`请输入${item.name}的值`"
                    ></jb-input>
                </n-form-item>
            </template>

            <template v-for="item in list" :key="item.id">
                <n-form-item
                    v-if="item.configKey == 'music_post_mediaid'"
                    label=""
                    class="flex justify-center items-center"
                >
                    <div
                        class="flex-col items-center cursor-pointer"
                        @click="toChooseMediaFile()"
                    >
                        <span>上传素材到微信服务器，获取MediaId</span>

                        <img
                            v-if="temporaryUrl"
                            class="w-100px mt-10"
                            :src="temporaryUrl"
                            style="height: auto"
                            alt=""
                        />

                        <div
                            v-else
                            class="w-100px h-100px mt-10 flex-center"
                            style="background-color: #cdcde6"
                        >
                            <jb-icon
                                v-if="state === 'pending'"
                                icon="eos-icons:bubble-loading"
                                width="40"
                                color="#ffffff"
                            ></jb-icon>
                            <jb-icon
                                v-else
                                icon="fluent:add-24-filled"
                                width="40"
                                color="#747d8c"
                            ></jb-icon>
                        </div>
                    </div>
                    <input
                        ref="mediaFileRef"
                        type="file"
                        name=""
                        accept="image/*"
                        class="hidden"
                        @change="uploadMedia($event)"
                    />
                </n-form-item>
            </template>
        </n-form>

        <template #footer>
            <div class="flex justify-end">
                <jb-btn type="primary" @click="submit">保存</jb-btn>
            </div>
        </template>
    </n-card>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { JBoltApi, Rules } from '@/utils'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        id: string
    }>(),
    {
        id: ''
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
const mediaFileRef = ref<Element | null>()

const state = ref('')
const temporaryUrl = ref('')

function toChooseMediaFile() {
    if (state.value == 'pending') {
        window?.$message.warning('正在上传，请稍后')
        return
    }
    mediaFileRef?.value[0].click()
}

function uploadMedia(e: any) {
    console.dir(e.target.files)
    if (e.target.files.length <= 0) {
        return
    }

    const file = e.target.files[0]

    if (parseFloat((file.size / 1024).toFixed(2)) > 100) {
        window?.$message!.warning('上传限制不能超过:100.0KB')
        return
    }
    return new Promise((resolve, reject) => {
        console.log('上传内容', file)
        state.value = 'pending'
        JBoltApi.tryPost<ResData>(
            `/api/admin/wechatConfig/uploadWechatMusicImgMedia/${props.id}`,
            { file: file },
            {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                onUploadProgress: function (progressEvent) {
                    // 处理原生进度事件
                    // 打印 progressEvent 对象查看属性
                    // 获取两个重要参数，计算上传进度，
                    // 最后保留1位小数
                    // if (next) {
                    //     const progress = progressEvent.total
                    //         ? (progressEvent.loaded / progressEvent.total) * 100
                    //         : 0
                    //     next({
                    //         size: progressEvent.total ?? 0,
                    //         loaded: progressEvent.loaded,
                    //         percent: progress
                    //     })
                    // }
                }
            }
        )
            .then((res) => {
                state.value = 'fulfilled'
                console.log('上传返回', res.data)
                list.value[0].configValue = res.data

                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = function (res) {
                    console.log('base64', res.target.result)
                    temporaryUrl.value = reader.result as string
                }

                resolve(res.data)
            })
            .catch((err) => {
                state.value = 'rejected'
                reject(err)
            })
            .finally(() => {
                state.value = ''
            })
    })
}

interface BucketType {
    id: string
    type: number
    name: string
    briefInfo: string
    needCheckSign: boolean
}

const form = useResetableData<BucketType>({
    id: '',
    type: 1,
    name: '',
    briefInfo: '',
    needCheckSign: false
})
const rules: FormRules = {
    type: new Rules().required('请选择应用类型').value,
    name: new Rules().required('请输入应用名称').value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()
    let url = '/api/admin/wechatConfig/submitExtraConfig'
    await JBoltApi.tryPost(url, {
        mpId: props.id,
        configs: list.value
    })
    state.value = ''

    loadData()

    return true
}

const list = ref<ResData[]>()

function loadData() {
    JBoltApi.get<ResData>(`/api/admin/wechatConfig/extraMgr/${props.id}`).then(
        ({ result }) => {
            list.value = result.data ?? []
        }
    )
}

onMounted(() => {
    if (props.id) {
        loadData()
    }
})
</script>

<style scoped></style>
